package com.cobra.json2tree;

import com.cobra.TreeNode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Tree2JsonUtil {

    private static final String ARRAY = JsonNodeType.ARRAY.name();

    private static ObjectMapper mapper = new ObjectMapper();

    private static List<Object> arrayTreeNode2json(TreeNode arrayNode) throws Exception {
        List<Object> list = new LinkedList<>();
        arrayNode.getChildren().forEach(childNode->{
            try {
                if(childNode.getChildren().isEmpty()){
                    list.add(childNode.getValue());
                }else {
                    list.add(tree2json(childNode));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return list;
    }

    private static Map<String, Object> tree2json(TreeNode treeRoot) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<TreeNode> children = treeRoot.getChildren();
        children.forEach(childNode -> {
                    try {
                        String type = childNode.getType();
                        switch (type) {
                            case "ARRAY":map.put(childNode.getName(),arrayTreeNode2json(childNode));
                                break;
                            case "OBJECT":
                                map.put(childNode.getName(), tree2json(childNode));
                                break;

                            default:
                                map.put(childNode.getName(), childNode.getValue());
                                break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
        );
        return map;
    }

    public static JsonNode tree2JsonNode(TreeNode root) throws Exception {
        return mapper.readTree(mapper.writeValueAsString(tree2json(root)));
    }
}
